package com.health.viewscontrols.medical.device.bo;

import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import com.blankj.utilcode.util.ToastUtils;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.health.ble.HexUtil;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.nova.health.ble.callback.OnScanCallback;
import com.nova.health.ble.callback.OnWriteCallback;
import com.nova.health.ble.device.MyBleDevice;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.BleHeartOxygenConversion;
import com.novabluetooth.views.XueYangHexUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class BOKrkActivity1 extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE =
            UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    public final static UUID UUID_NOTIFY =
            UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
    public final static UUID UUID_WRITE =
            UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    private String mBloodOxygen;//血氧值
    private String mHeartRate;//心率值
    private Disposable disposable;

    @Override
    public void startDevice() {
        showProgressDialog("正在搜索" + deviceEnum.getTitle() +  "设备");
        if (!isConnected) {
            mBleDevice.scanBleDevice(true, new OnScanCallback() {
                @Override
                public void onFinish() { }

                @Override
                public void onScanning(BluetoothDevice device, int rssi, byte[] scanRecord) {
                    Log.e(TAG, "onScanning: " + device.getName() + device.getAddress() );
                    if (deviceEnum.getMac().equals(device.getAddress())) {
                        Log.e(TAG, "onScanning: find...." + device.getName() + device.getAddress() );
                        blueToothState.setText("蓝牙开始连接");
                        mBleDevice.setMAC(deviceEnum.getMac());
                        mBleDevice.connect(deviceEnum.getMac());
                        mBleDevice.setConnect(true);
                        mBleDevice.stopScan();
                    }
                }
            });
        } else {
            cancelProgressDialog();
            ToastUtils.showShort("设备已连接，请等待测量结果");
        }
    }

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bo_pc_60f);

        mBleDevice.setDevice_Service_UUID(UUID_SERVICE);
        mBleDevice.setDevice_Notify_UUID(UUID_NOTIFY);
        mBleDevice.setDEVICE_write_UUID(UUID_WRITE);
        mBleDevice.setConnectChangedListener(new OnDeviceConnectChangedListener() {
            @Override
            public void onConnected() {
                runOnUiThread(() -> {
                    //连接成功
                    Log.e(TAG, "onConnectSuccess: ");
                    isConnected = true;
                    blueToothState.setText("蓝牙已连接");
                    cancelProgressDialog();
                    interval();
                });
            }

            @Override
            public void onDisconnected() {
                runOnUiThread(() -> {
                    isConnected = false;
                    blueToothState.setText("蓝牙连接失败");
                    cancelProgressDialog();
                    setStatusPre();
                    stopTimer();
                });
            }
        });
        startDevice();
    }

    @Override
    public void update(String hexStr) {
        analysisData(hexStr);
    }

    //中间数据
    private List<String> tempArrays = new ArrayList<>();

    /**
     * 解析数据
     * @param formatHexString
     */
    private void analysisData(String formatHexString) {
        Log.e(TAG, "analysisData: " + formatHexString );
        String[] strings = XueYangHexUtils.formatHexString(
                HexUtil.hexStringToBytes(formatHexString), true).split(" ");
        tempArrays.clear();
        if(strings.length < 8){
            return;
        }else if(strings.length > 12){
            for(int i = 0; i< 12 ; i++){
                tempArrays.add(strings[i]);
            }
        }else{
            tempArrays.addAll(Arrays.asList(strings));
        }

        if(BleHeartOxygenConversion.isHeartRateTrue(tempArrays) && BleHeartOxygenConversion.isDataTrue(tempArrays)){
            //检测数据长度是否符合 不符合略过
            mBloodOxygen = Integer.parseInt(tempArrays.get(5), 16)+"";//血氧浓度
            mHeartRate = Integer.parseInt(tempArrays.get(7)+tempArrays.get(6), 16)+"";//脉搏（心率）
            tv_state.setText("实时测量结果");
            tv_result.setText("脉率:" + mHeartRate + "bpm\t\t"+"血氧:" + mBloodOxygen + "%");
            Log.e(TAG, "脉率:" + mHeartRate + "bpm\t\t"+"血氧:" + mBloodOxygen + "%");
        }
    }

    private void setStatusPre() {
        tv_state.setText("获取测量结果成功");
        tv_result.setText("脉率:" + mHeartRate + "bpm\t\t"+"血氧:" + mBloodOxygen + "%");
        Log.e(TAG, "setStatusPre: " +  mBloodOxygen + "/" + mHeartRate);
        if (!TextUtils.isEmpty(mBloodOxygen)) {
            DeviceShowSaveData.getDataShow( mBloodOxygen + "/" + mHeartRate, BluetoothConstant.XUEYANG_LIKANG_KRK);
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            mBleDevice.stopScan();
            mBleDevice.setConnect(false);
            mBleDevice.disconnect();
            mBleDevice.close();
            stopTimer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void interval() {
        stopTimer();
        disposable = Observable.interval(5000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Long aLong) throws Exception {
                        Log.e(TAG, "accept: " + aLong );
                        if (isConnected) {
                           writeBuff("aa550f038401e0");
                           writeBuff("aa550f03850124");
                           writeBuff("aa550f03800239");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    private void writeBuff(String command) {
        mBleDevice.writeBuffer(command, new OnWriteCallback() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "write onSuccess: ");
            }

            @Override
            public void onFailed(int state) {
                Log.e(TAG, "write onFailed: " + state);
            }
        });
    }

    /**
     * 停止定时执行
     */
    protected void stopTimer() {
        try {
            if (null != disposable) {
                disposable.dispose();
                disposable = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
